#
# EncoderLibrary.py
#
# This work is released under the GNU GPL, version 2 or later.
#

from Library import *
from Utils.Settings import *
import os

class EncoderTrack(Track):
	def __init__(self):
		Track.__init__(self,EncoderLibrary.singleton())
	
	def copyFieldsFrom(self,track):
		try: self.title = track.title
		except: pass
		try: self.artist = track.artist
		except: pass
		try: self.album = track.album
		except: pass
		try: self.trackNum = track.trackNum
		except: pass
		try: self.trackCount = track.trackCount
		except: pass
		try: self.totalTime = track.totalTime
		except: pass
		try: self.genre = track.genre
		except: pass
		try: self.year = track.year
		except: pass
		try: self.compilation = track.compilation
		except: pass
		try: self.originalLocation = track.originalLocation
		except: pass
		try: self.location = track.originalLocation
		except: pass

	def setRipStatus(self,status):
		#print status
		if status['Status'] in ['Begin','Ripping','Encoding']:
			self.ripStatus = 'ripping'
		elif status['Status']=='EndTrack':
			if status.get('Interrupted',False):
				self.ripStatus = 'idle'
			elif status['Source']=='Ripper':
				self.ripStatus = 'ripped'
		self.emit(PYSIGNAL("ripStatus"),(self,status))

	def kill(self):
		#print "killing",self,self.originalLocation
		try: os.remove(self.originalLocation)
		except: pass

class EncoderLibrary(FileLibrary):
	def __init__(self):
		FileLibrary.__init__(self)
	
	def load(self):
		self.readXMLFile()
		if not self.playlistWithName("Encoder"):
			self.addNewPlaylist("Encoder")
		self.playlist = self.playlistWithName("Encoder")
		self.timer = None
		if self.playlist.trackCount() and Settings.settings().get("Encoding",True):
			self.timer = QTimer()
			QObject.connect(self.timer,SIGNAL("timeout()"),self.resumeEncoding)
			self.timer.start(5000)
	
	def resumeEncoding(self):
		#print "resuming encoder"
		self.timer.stop()
		from LMusicEncoder import LMusicEncoder
		encoder = LMusicEncoder.singleton()
		if not encoder.isEncoding():
			encoder.encodeNextTrack()

	def libraryPath(self):
		return Library.mainLibrary().libraryPath()
		
	def xmlPath(self):
		return os.path.join(self.musicPath(),'EncoderLibrary.xml')

	def musicPath(self):
		return Settings.settings().get("Encoder Library Path",self.defaultMusicPath())
	
	def defaultMusicPath(self):
		return os.path.join(self.libraryPath(),'EncoderMusic')

	def trackForKind(self,trackPList):
		return EncoderTrack()

	def readXMLFile(self):
		#print "reading Encoder XML file"
		fileName = self.xmlPath()
		if os.path.exists(fileName):
			try:
				reader = PListReader()
				pList = reader.parse(fileName)
				#print "reading EncoderLibrary",pList
				self.setPList(pList[0])
				self.sanityCheck()
			except: return False
			self.emit(PYSIGNAL("readLibrary"),(self,None))
			return True
		else:
			return False

	#
	# make sure the files actually exist
	#
	def sanityCheck(self):
		index = 0
		trackIDs = self._tracks.keys()
		badIDs = []
		for trackID in trackIDs:
			track = self._tracks[trackID]
			location = track.location
			if not os.path.exists(location):
				badIDs.append(trackID)
				index = index+1
		self.removeTrackIDsFromAllPlaylists(badIDs)
		self.killTrackIDs(badIDs)

	def writeXMLFile(self):
		#import traceback
		#print traceback.print_stack()
		writer = PListWriter()
		pList = self.getPList()
		writer.unparse([pList],self.xmlPath())		

	def static_singleton():
		global _encoderLibrary
		if not _encoderLibrary:
			_encoderLibrary = EncoderLibrary()
			_encoderLibrary.load()
		return _encoderLibrary
	singleton = staticmethod(static_singleton)

_encoderLibrary = None
